<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        #box{
            width: 300px;
            height: 50px;
            line-height: 50px;
            padding: 20px;
            font-size: 30px;
            color:#f00;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <h1>AJAX</h1>
    <hr>

    加数1: <input type="text" id="num1"><br>
    加数2: <input type="text" id="num2"><br>

    <button onclick="add()">相加</button>
    

    <hr>
    <div id="box"></div>


    <script>
        function add() {
            // 获取表单数据
            var num1 = document.getElementById('num1').value;
            var num2 = document.getElementById('num2').value;

            // 创建XHR请求对象
            var xhr = new XMLHttpRequest();
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 获取服务端的响应文本
                    box.innerHTML = xhr.responseText;
                }
            }
            
            // 请求初始化
            xhr.open('post', './php/3.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            // 发送请求
            xhr.send('a='+num1+'&b='+num2);
        }

    
    </script>
</body>
</html>